package com.domcer.ultra.menu.application.listener;

import com.domcer.ultra.menu.application.cache.MenuCache;
import com.domcer.ultra.menu.domain.MenuDomain;
import com.domcer.ultra.menu.engine.MenuManager;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;

/**
 * @author Sensen
 */
public class PlayerInteractListener implements org.bukkit.event.Listener {
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        ItemStack itemInHand = player.getInventory().getItemInMainHand();
        if (itemInHand.getType() == Material.AIR) {
            return;
        }

        Action action = event.getAction();
        String materialName = itemInHand.getType().toString();

        //TODO MAKE A LOCK -> BECAUSE RIGHT_CLICK WILL BE TRIGGER TWICE WHEN CLICK BLOCK
        if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
            handleClick(player, materialName, true);
        }
        if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
            handleClick(player, materialName, false);
        }
    }

    public static void handleClick(Player player, String materialName, boolean isRightClick) {
        MenuDomain menuDomain;
        if (isRightClick) {
            menuDomain = MenuCache.getRightMenuDomain(materialName);
        } else {
            menuDomain = MenuCache.getLeftMenuDomain(materialName);
        }
        MenuManager.open(player, menuDomain);
    }
}
